from app import db

def UpdateInstance(instance, data=None):
    def insert(obj):
        try:
            db.session.add(obj)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(f"Error: {e}")

    if instance is None or data is None:
        return

    columns = {column.name for column in instance.__table__.columns}
    if data:
        common_fields = columns & data.keys()
        for column_name in common_fields:
            if data[column_name] is not None:
                setattr(instance, column_name, data[column_name])
    insert(instance)

def PackInstance(instance):
    if not instance:
        return {}

    instance_dict = {column.name: getattr(instance, column.name) for column in instance.__table__.columns}
    return instance_dict

def QueryOneInstance(class_, filter_):
    return class_.query.filter_by(**filter_).first()

def QueryOrCreateOneInstance(class_, filter_):
    ins =  class_.query.filter_by(**filter_).first()
    if ins is None:
        ins = class_(**filter_)
    return ins



